package org.dawfinn.droiditarian.deedsource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dawfinn.droiditarian.data.Deed;
import org.dawfinn.droiditarian.proto.Droiditarian;

import android.util.Log;

public class InternetDeedSource implements DeedSource {

	private final String path;
	private static final String BEFORE_PARAM = "beforeDate";

	private static final String UTF_8 = "UTF-8";
	private static final DateFormat dateFormatter = DateFormat.getInstance();

	public InternetDeedSource(String path) {
		this.path = path;
	}

	public List<Deed> getDeeds() throws IOException {
		return parseDeeds(new URL(path).openStream());
	}

	public List<Deed> getDeeds(Date beforeDate) throws IOException {
		String pathWithArgument = path + "?" + BEFORE_PARAM + "="
				+ URLEncoder.encode(dateFormatter.format(beforeDate), UTF_8);
		Log.i("InternetDeedSource", path);
		return parseDeeds(new URL(pathWithArgument).openStream());
	}

	private List<Deed> parseDeeds(InputStream in) throws IOException {
		List<Deed> result = new ArrayList<Deed>();
		Droiditarian.Deed proto;

		while ((proto = Droiditarian.Deed.parseDelimitedFrom(in)) != null) {
			result.add(new Deed(proto.getName(), proto.getDescription(), proto
					.getExplanation(), proto.getMoreInfo(), proto.getKey(),
					new Date(proto.getReleaseDate())));
		}

		return result;
	}
}
